//
//  Problem539.swift
//  TestProject
//
//  Created by 武侠 on 2021/5/26.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit

/*
 539. 最小时间差
 给定一个 24 小时制（小时:分钟 "HH:MM"）的时间列表，找出列表中任意两个时间的最小时间差并以分钟数表示。

 示例 1：
     输入：timePoints = ["23:59","00:00"]
     输出：1
 示例 2：
     输入：timePoints = ["00:00","23:59","00:00"]
     输出：0
 提示：
     2 <= timePoints <= 2 * 104
     timePoints[i] 格式为 "HH:MM"
 */
@objcMembers class Problem539: NSObject {
    func solution() {
        print(findMinDifference(["23:59","00:00"]))
        print(findMinDifference(["02:10","23:59","00:00"]))
        print(findMinDifference(["05:31","22:08","00:35"]))
    }
    
    /*
     1: 将时间转换成分钟数，然后存储到数组中list[1441]（2400 = 1400）
     2: 遍历数组list，统计2个时间之间的间距，寻找最小值

     注意：
     1: 如果在转换成分钟数时，当前位置已经存储了，那么最小时就是0
     2: 比较2个时间的间距时，最后还要比较第一个和最后一个的间距，因为钟是圆的
     */
    func findMinDifference(_ timePoints: [String]) -> Int {
        var list:[Int] = Array(repeating: 0, count: 1441)
        var t = 0
        for time in timePoints {
            t = changeToInt(time)
            print(t)
            list[t] += 1
            if list[t] > 1 {
                return 0
            }
        }

        
        var cha = Int.max
        var lastI = 0
        var firstI = -1
        for (i, n) in list.enumerated() {
            if n == 1 {
                if lastI != 0 {
                    cha = min(cha, i - lastI)
                }
                if firstI == -1 {
                    firstI = i
                }
                
                lastI = i
            }
        }
        cha = min(cha, list.count - 1 - lastI + firstI)
        
        return cha
    }
    
    func changeToInt(_ time: String) -> Int {
        var n = 0
        for (i, c) in time.enumerated().reversed() {
            if i == 4 {
                n += Int(c.asciiValue!) - 48
            } else if i == 3 {
                n += (Int(c.asciiValue!) - 48) * 10
            } else if i == 1 {
                n += (Int(c.asciiValue!) - 48) * 60
            } else if i == 0 {
                n += (Int(c.asciiValue!) - 48) * 60 * 10
            }
        }
        return n
    }
}
